package com.yanx.auth.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.Producer;
import com.yanx.auth.cache.CaptchaCache;
import com.yanx.auth.service.AuthService;
import com.yanx.common.constant.CacheConstants;
import com.yanx.common.exception.BusinessException;
import com.yanx.common.security.model.RegisterDto;
import com.yanx.common.security.service.LoginExtendService;
import com.yanx.framework.config.YanxConfig;
import com.yanx.system.client.SystemRpc;
import com.yanx.system.client.dto.RouterVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录服务实现类
 *
 * @author gotanks
 * @date 2021-02-26 13:46:00
 */
@Service
public class AuthServiceImpl implements AuthService {

    @DubboReference(version = "1.0")
    private SystemRpc systemRpc;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private LoginExtendService loginExtendService;

    @Override
    public List<RouterVo> getRouters() {
        List<RouterVo> routers = systemRpc.getCurrentRouters();
        return routers;
    }

    @Override
    public Map<String, Object> getCode() {
        Map<String, Object> result = new HashMap<>();
        boolean captchaEnabled = systemRpc.captchaEnabled();
        result.put("captchaEnabled", captchaEnabled);
        if (captchaEnabled) {
            // 保存验证码信息
            String uuid = IdUtil.simpleUUID();
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

            String capStr, code = null;
            BufferedImage image = null;

            // 生成验证码
            String captchaType = YanxConfig.getCaptchaType();
            if ("math".equals(captchaType)) {
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
                image = captchaProducerMath.createImage(capStr);
            } else if ("char".equals(captchaType)) {
                capStr = code = captchaProducer.createText();
                image = captchaProducer.createImage(capStr);
            }

            //放入缓存
            CaptchaCache.INSTANCE.set(new String[]{uuid}, code);

            // 转换流信息写出
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            try {
                ImageIO.write(image, "jpg", os);
            } catch (IOException e) {
                throw new BusinessException(e);
            }

            result.put("uuid", uuid);
            result.put("img", Base64.encode(os.toByteArray()));
        }
        return result;
    }

    @Override
    public void register(RegisterDto user) {
        boolean registerEnabled = systemRpc.registerEnabled();
        if (!registerEnabled) {
            throw new BusinessException("当前系统没有开启注册功能！");
        }
        //校验验证码
        loginExtendService.validateCaptcha(user.getUsername(), user.getCode(), user.getUuid());

        //注册
        systemRpc.register(user.getUsername(), user.getPassword());
        
    }
}
